package de.bluetooth.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class BluetoothClient extends Thread 
{
	public boolean active;
	public boolean isConnected;
	Handler messageHandler;
	
	public BluetoothSocket socket;
	public BluetoothDevice device;
	
	UUID uid;
	
	public BluetoothClient(Handler messageHandler)
	{
		super();
		this.messageHandler=messageHandler;
		
		active=true;
		isConnected=false;
		
		uid = UUID.fromString("f5efb9d2-deaf-4af8-a304-8739fe2109ab");
	}
	
	public BluetoothClient(Handler messageHandler,BluetoothDevice toDevice)
	{
		super();
		this.messageHandler=messageHandler;
		this.device = toDevice;
		
		active=true;
		isConnected=false;
		
		uid = UUID.fromString("f5efb9d2-deaf-4af8-a304-8739fe2109ab");
	}
	
	public BluetoothClient(Handler messageHandler,BluetoothSocket targetSocket)
	{
		super();
		this.messageHandler=messageHandler;
		this.socket = targetSocket;
		this.device = targetSocket.getRemoteDevice();
		isConnected=true;
		
		active=true;
		
		uid = UUID.fromString("f5efb9d2-deaf-4af8-a304-8739fe2109ab");
	}
	
	public synchronized void cancel()
	{
		Log.i("BluetoothClient", "Cancel");
		if(socket!=null)
			try {
				socket.close();
				Log.i("BluetoothClient", "Disconnected from "+device.getName());
			} catch (IOException e) {}
		
		device = null;
		socket=null;
		
		active=false;
	}
	
	public void run() 
	{
		String currentMessage = null;
		try
		{
			while(active)
			{
				if(!isConnected)
				{
					//Try to connect to server
					if(socket == null)
						socket = device.createRfcommSocketToServiceRecord(uid);
					
		            socket.connect();
		            isConnected=true;
				}
				else
				{
					//Wait for Messages
					currentMessage=null;
					currentMessage = receiveMessage();
						
					if(currentMessage!=null)
						Log.i("BluetoothClient", "Received Message: "+currentMessage);	
				}
			}
		}catch(Exception e)
		{
			handleError(e);
		}
	}
	
	public void disconnect()
	{
		if(socket!=null)
			try {
				socket.close();
				Log.i("BluetoothClient", "Disconnected from "+device.getName());
			} catch (IOException e) {}
		
		device = null;
		socket=null;
		isConnected=false;
	}
	
	public void sendMessage(String message)
	{
		try {
            socket.getOutputStream().write(message.getBytes());
            Log.i("BluetoothClient","<< "+message);
        } catch (IOException e) {
        	Log.i("BluetoothClient","Failed to send message "+message);
        }
	}
	
	protected String receiveMessage()
	{	
		Log.i("BluetoothClient","Try to receive Message");
		
		byte[] buffer = new byte[1024];
        int bytes;
        
        String message = null;
        
		try 
		{
			InputStream input = socket.getInputStream();
			
			bytes = input.read(buffer);
			message = new String(buffer,0,bytes);
			Log.i("BluetoothClient",">> "+message);
			
            messageHandler.obtainMessage(1,message)
            .sendToTarget();
			
		} catch (IOException e) 
		{
			Log.i("BluetoothClient","Failed to receive Message");
			this.disconnect();
		}
		
		return message;
	}
	
	public void handleError(Exception exception)
	{
		String deviceName="None";
		
		if(device!=null)
			deviceName = device.getName();
			
		
		System.out.println("Exception occured on client: "+ deviceName + " - "+exception);
		Log.i("Exception occured on client", deviceName + " - "+ exception);
	}
	
}
